package com.kyivmohyla.kma2.dao;

import com.kyivmohyla.kma2.dao.mapper.RefsRowMapper;
import com.kyivmohyla.kma2.model.Refs;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;

public class RefsDaoJdbc extends JdbcDaoSupport implements RefsDao {

    @Override
    public Refs getById(int id) throws DataAccessException {
        return getJdbcTemplate()
                .queryForObject(
                        "SELECT refs.service_id, refs.equipment_id FROM refs WHERE refs.service_id = ?",
                        new Object[]{id}, new RefsRowMapper());
    }

    @Override
    public List<Refs> getAll() throws DataAccessException {
        return getJdbcTemplate()
                .query("SELECT refs.service_id, refs.equipment_id FROM refs ORDER BY refs.service_id",
                        new RefsRowMapper());
    }

    @Override
    public void create(Refs refs) throws DataAccessException {
        getJdbcTemplate()
                .update("INSERT INTO refs (refs.service_id, refs.equipment_id) VALUES (?, ?)",
                        refs.getServiceId(),
                        refs.getEquipmentId());
    }

    @Override
    public void update(Refs refs) throws DataAccessException {
        getJdbcTemplate()
                .update("UPDATE refs SET refs.equipment_id = ? WHERE refs.service_id = ?",
                        refs.getEquipmentId(),
                        refs.getServiceId());
    }

    @Override
    public void delete(Refs refs) throws DataAccessException {
        String query = "DELETE FROM refs WHERE refs.service_id = " + refs.getServiceId() + " AND refs.equipment_id = " + refs.getEquipmentId();
//        getJdbcTemplate().update("DELETE FROM refs WHERE refs.service_id = ? AND refs.equipment_id = ?",
//                refs.getServiceId(),refs.getEquipmentId());
        getJdbcTemplate().update(query);
    }

    @Override
    public void deleteList(List<Refs> objs) throws DataAccessException {
        for (Refs refs : objs) {
            delete(refs);
        }
    }

    @Override
    public void addList(List<Refs> objs) throws DataAccessException {
        for (Refs refs : objs) {
            create(refs);
        }
    }

}
